{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Responsible AI dashboard for Time Series Forecasting\n",
    "_**Orange Juice Sales Forecasting**_\n",
    "\n",
    "Note: Time series forecasting is not yet supported by raiwidgets. This notebook uses an experimental setting to enable it. However, the API and functionality may change at any point in the future without warning. We suggest you hold off on using it until the official release.\n",
    "\n",
    "## Contents\n",
    "1. [Introduction](#introduction)\n",
    "1. [Data](#data)\n",
    "1. [Train](#train)\n",
    "1. [Responsible AI Dashboard](#analyze)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction<a id=\"introduction\"></a>\n",
    "In this example, we use sktime to train and assess a time-series forecasting model for multiple time-series.\n",
    "\n",
    "The examples in the follow code samples use the University of Chicago's Dominick's Finer Foods dataset to forecast orange juice sales. Dominick's was a grocery chain in the Chicago metropolitan area."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1670990788014
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sktime.forecasting.arima import AutoARIMA\n",
    "from sktime.forecasting.base import ForecastingHorizon\n",
    "from sktime.forecasting.model_selection import temporal_train_test_split"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data<a id=\"data\"></a>\n",
    "You are now ready to load the historical orange juice sales data. We will load the CSV file into a plain pandas DataFrame; the time column in the CSV is called _WeekStarting_, so it will be specially parsed into the datetime type.\n",
    "Each row in the DataFrame holds a quantity of weekly sales for an OJ brand at a single store. The data also includes the sales price, a flag indicating if the OJ brand was advertised in the store that week, and some customer demographic information based on the store location. For historical reasons, the data also include the logarithm of the sales quantity. The Dominick's grocery data is commonly used to illustrate econometric modeling techniques where logarithms of quantities are generally preferred.    \n",
    "\n",
    "The task is now to build a time-series model for the _Quantity_ column. It is important to note that this dataset is comprised of many individual time-series - one for each unique combination of _Store_ and _Brand_. To distinguish the individual time-series, we define the **time_series_id_features** the columns whose values determine the boundaries between time-series: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1670990899201
    }
   },
   "outputs": [],
   "source": [
    "time_column_name = \"WeekStarting\"\n",
    "time_series_id_features = [\"Store\", \"Brand\"]\n",
    "dataset_location = \"https://raw.githubusercontent.com/Azure/azureml-examples/2fe81643865e1f4591e7734bd1a729093cafb826/v1/python-sdk/tutorials/automl-with-azureml/forecasting-orange-juice-sales/dominicks_OJ.csv\"\n",
    "data = pd.read_csv(dataset_location, parse_dates=[time_column_name])\n",
    "\n",
    "# Drop the columns 'logQuantity' as it is a leaky feature.\n",
    "data.drop(\"logQuantity\", axis=1, inplace=True)\n",
    "\n",
    "# Set up multi index with time series ID columns and time column.\n",
    "data.set_index(time_series_id_features + [time_column_name], inplace=True, drop=True)\n",
    "data = data.groupby(time_series_id_features).apply(lambda group: group.loc[group.name].asfreq(\"W-THU\").interpolate())\n",
    "data.sort_index(inplace=True, ascending=[True, True, True])\n",
    "\n",
    "data.head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1670990902872
    }
   },
   "outputs": [],
   "source": [
    "nseries = data.groupby(time_series_id_features).ngroups\n",
    "print(\"Data contains {0} individual time-series.\".format(nseries))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For demonstration purposes, we extract sales time-series for just a few of the stores:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1670990905562
    }
   },
   "outputs": [],
   "source": [
    "use_stores = [2, 5, 8]\n",
    "use_brands = ['tropicana', 'dominicks', 'minute.maid']\n",
    "data_subset = data.loc[(use_stores, use_brands, slice(None)), :]\n",
    "nseries = data_subset.groupby(time_series_id_features).ngroups\n",
    "print(f\"Data subset contains {nseries} individual time-series.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data Splitting\n",
    "We now split the data into a training and a testing set for later forecast evaluation. The test set will contain the final 20 weeks of observed sales for each time-series. The splits should be stratified by series, so we use a group-by statement on the time series identifier columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1670990907583
    }
   },
   "outputs": [],
   "source": [
    "target_column_name = \"Quantity\"\n",
    "\n",
    "y = pd.DataFrame(data_subset[target_column_name])\n",
    "X = data_subset.drop(columns=[target_column_name])\n",
    "fh_dates = pd.DatetimeIndex(y.index.get_level_values(2).unique().sort_values().to_list()[-20:], freq='W-THU')\n",
    "fh = ForecastingHorizon(fh_dates, is_relative=False)\n",
    "y_train, y_test, X_train, X_test = \\\n",
    "    temporal_train_test_split(\n",
    "        y=y,\n",
    "        X=X,\n",
    "        test_size=20)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train<a id=\"train\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can now submit a new training run. Depending on the data and number of iterations this operation may take several minutes.\n",
    "Information from each iteration will be printed to the console.  Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# When using sktime directly we need to drop the time and time series ID columns.\n",
    "model = AutoARIMA(suppress_warnings=True, error_action=\"ignore\")\n",
    "model.fit(y=y_train, X=X_train, fh=fh)\n",
    "model.predict(fh=fh, X=X_test).head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.predict_quantiles(fh=fh, X=X_test, alpha=[0.025, 0.975]).head()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Responsible AI Dashboard<a id=\"analyze\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "from raiwidgets import ResponsibleAIDashboard\n",
    "from responsibleai import RAIInsights, FeatureMetadata\n",
    "\n",
    "# merge X, y, and the time and time series ID features into a single DataFrame\n",
    "train = X_train.join(y_train).join(X_train.index.to_frame(index=True))\n",
    "test = X_test.join(y_test).join(X_test.index.to_frame(index=True))\n",
    "train.reset_index(drop=True, inplace=True)\n",
    "test.reset_index(drop=True, inplace=True)\n",
    "\n",
    "feature_metadata = FeatureMetadata(\n",
    "    time_series_id_features=time_series_id_features, \n",
    "    categorical_features=time_series_id_features,\n",
    "    datetime_features=[time_column_name])\n",
    "insights = RAIInsights(\n",
    "    model=model,\n",
    "    train=train,\n",
    "    test=test,\n",
    "    task_type=\"forecasting\",\n",
    "    target_column=target_column_name,\n",
    "    feature_metadata=feature_metadata,\n",
    "    forecasting_enabled=True)\n",
    "\n",
    "ResponsibleAIDashboard(insights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "authors": [
   {
    "name": "jialiu"
   }
  ],
  "categories": [
   "SDK v1",
   "how-to-use-azureml",
   "automated-machine-learning"
  ],
  "category": "tutorial",
  "celltoolbar": "Raw Cell Format",
  "compute": [
   "Remote"
  ],
  "datasets": [
   "Orange Juice Sales"
  ],
  "deployment": [
   "Azure Container Instance"
  ],
  "exclude_from_index": false,
  "framework": [
   "Azure ML AutoML"
  ],
  "friendly_name": "Forecasting orange juice sales with deployment",
  "index_order": 1,
  "kernel_info": {
   "name": "python38-azureml"
  },
  "kernelspec": {
    "display_name": "Python 3",
    "language": "python",
    "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  },
  "microsoft": {
   "host": {
    "AzureML": {
     "notebookHasBeenCompleted": true
    }
   }
  },
  "nteract": {
   "version": "nteract-front-end@1.0.0"
  },
  "tags": [
   "None"
  ],
  "task": "Forecasting",
  "vscode": {
   "interpreter": {
    "hash": "6424d405450b15a93ca3015242fc1e51ac658b1b4015ae2fef5559269d9e1e0c"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
